package com.zhl.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取接口路径
        String uri = req.getRequestURI();
        //接口名
        String name = uri.substring(uri.lastIndexOf("/") + 1);
        Class<? extends BaseServlet> aClass = this.getClass();

        Method method;
        try {
            method = aClass.getMethod(name,HttpServletRequest.class,HttpServletResponse.class);
            //代理执行
            method.invoke(aClass.newInstance(),req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected Map<String, String> getParam(HttpServletRequest request) {
        Map<String, String> resultMap = new HashMap<>();
        Map<String, String[]> map = request.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = map.entrySet();
        for (Map.Entry<String, String[]> entry : entries) {
            String[] value = entry.getValue();
            if (value.length > 1) {
                resultMap.put(entry.getKey(), Arrays.toString(value));
            } else {
                resultMap.put(entry.getKey(), value[0]);
            }
        }
        return resultMap;
    }
}
